package swt.screen;

import java.io.IOException;
import java.util.logging.Logger;

import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import swt.commons.Const;
import swt.commons.LogUtil;
import swt.commons.ResourceUtil;
import swt.commons.Utils;
import swt.form.BaseForm;

import com.swtdesigner.SWTResourceManager;

public class SetupPasswordWindow {

	private static Logger log = LogUtil.getLogger();
	
	private Button btnCancel;
	private Text txtConfirmPass;
	private Button btnSetPassword;
	private Text txtPassword;
	protected Shell parent;
	protected Shell oneself;
	private CLabel clblSetPassword;
	private CLabel clblConfirm;
	private BaseForm form = new BaseForm();

	private int action = -1;
	private boolean exitFlag = true;
	private String language;
	
	/**
	 * Constructor
	 * @param parent 
	 * @param action
	 */
	public SetupPasswordWindow(Shell parent, int action){
		this.parent = parent;
		this.action = action;
	}

	/**
	 * Open the window
	 */
	public boolean open() {
		try {
			ResourceUtil resourceUtil = ResourceUtil.getInstance();
			
			String password = resourceUtil.getProperty(Const.KEY_PASSWORD);
			form.setPassword(password);
			
			// If not found password, just skip password checking
			if (Utils.isNullEmpty(form.getPassword()) && this.action == Const.CHECK_PASS) {
				return true;
			}
			
			log.info("Open Setup Password Screen");
			
			// Check Language
			language = resourceUtil.getProperty(Const.KEY_LANGUAGE);
			// Setup language
			if (Utils.isNullEmpty(language)) {
				language = Const.LANGUAGE_EN;
				resourceUtil.setProperty(Const.KEY_LANGUAGE, language);
			}
			
			if (!Utils.isNullEmpty(form.getPassword())) {
				if (this.action == Const.CHECK_PASS) {
					log.info("MODE = CHECK_PASS");
				}
				else {
					log.info("MODE = EDIT_PASS");
					this.action = Const.EDIT_PASS;
				}
			}
			else {
				log.info("MODE = NEW_PASS");
			}
			
			createContents();
			
			oneself.open();
			oneself.layout();

			while (!oneself.isDisposed()) {
				if (!oneself.getDisplay().readAndDispatch()) {
					oneself.getDisplay().sleep();
				}
			}
			
			log.info("Close Setup Password Screen.");
		} 
		catch (Exception e) {
			log.severe("Exception." + e.getMessage());
		}
		
		return exitFlag;
	}

	/**
	 * Create contents of the window
	 * @throws IOException 
	 */
	protected void createContents() throws IOException {
		
		oneself = new Shell(this.parent, SWT.TITLE | SWT.BORDER | SWT.PRIMARY_MODAL);
		oneself.setSize(500, 130);
		oneself.setBackground(Const.COLOR_BASE_BGR);
		oneself.setImage(SWTResourceManager.getImage(Const.ICON_FILE));
		oneself.addListener(SWT.Traverse, new Listener() {
		    public void handleEvent(Event e) {
		        if (e.detail == SWT.TRAVERSE_ESCAPE) {
		            e.doit = false;
		            cancelAction();
		        }
		    }
		});
		
		Rectangle disRect = Display.getCurrent().getBounds();
		int x = (disRect.width - oneself.getSize().x) / 2;
		int y = (disRect.height - oneself.getSize().y) / 2;
		oneself.setLocation(x,y);

		if (this.action == Const.SETUP_PASS || this.action == Const.EDIT_PASS) {
			int startRow = 13;
			clblSetPassword = new CLabel(oneself, SWT.CENTER | SWT.SHADOW_OUT);
			clblSetPassword.setBounds(10, startRow, 100, 23);
			clblSetPassword.setFont(Const.FONT_BASE);
			clblSetPassword.setBackground(SWTResourceManager.getColor(244, 245, 255));
	
			txtPassword = new Text(oneself, SWT.PASSWORD | SWT.BORDER);
			txtPassword.setBounds(116, startRow, 262, 23);
			txtPassword.setTextLimit(50);
			txtPassword.setFont(Const.FONT_BASE);
			txtPassword.setBackground(Const.COLOR_TEXT_MUST_INPUT);
			txtPassword.addFocusListener(new FocusAdapter() {
				public void focusGained(FocusEvent e) {
					txtPassword.selectAll();
				}
			});
	
			startRow += 30;
			
			clblConfirm = new CLabel(oneself, SWT.CENTER | SWT.SHADOW_OUT);
			clblConfirm.setBounds(10, startRow, 100, 23);
			clblConfirm.setFont(Const.FONT_BASE);
			clblConfirm.setBackground(SWTResourceManager.getColor(244, 245, 255));
	
			txtConfirmPass = new Text(oneself, SWT.PASSWORD | SWT.BORDER);
			txtConfirmPass.setBounds(116, startRow, 262, 23);
			txtConfirmPass.setTextLimit(50);
			txtConfirmPass.setFont(Const.FONT_BASE);
			txtConfirmPass.setBackground(Const.COLOR_TEXT_MUST_INPUT);
			txtConfirmPass.addFocusListener(new FocusAdapter() {
				public void focusGained(FocusEvent e) {
					txtConfirmPass.selectAll();
				}
			});
		}
		else if (this.action == Const.CHECK_PASS){
			clblSetPassword = new CLabel(oneself, SWT.CENTER | SWT.SHADOW_OUT);
			clblSetPassword.setBounds(10, 13, 100, 23);
			clblSetPassword.setFont(Const.FONT_BASE);
			clblSetPassword.setBackground(SWTResourceManager.getColor(244, 245, 255));
	
			txtPassword = new Text(oneself, SWT.PASSWORD | SWT.BORDER);
			txtPassword.setBounds(116, 13, 262, 23);
			txtPassword.setTextLimit(10);
			txtPassword.setFont(Const.FONT_BASE);
			txtPassword.setBackground(Const.COLOR_TEXT_MUST_INPUT);
			txtPassword.addFocusListener(new FocusAdapter() {
				public void focusGained(FocusEvent e) {
					txtPassword.selectAll();
				}
			});
		}

		btnSetPassword = new Button(oneself, SWT.NONE);
		btnSetPassword.setBounds(384, 12, 100, 25);
		btnSetPassword.setFont(SWTResourceManager.getFont("Microsoft Sans Serif", 10, SWT.NONE));
		btnSetPassword.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent arg0) {
				setPassAction();
			}
		});
		
		btnCancel = new Button(oneself, SWT.NONE);
		btnCancel.setBounds(384, 43, 100, 25);
		btnCancel.setFont(SWTResourceManager.getFont("Microsoft Sans Serif", 10, SWT.NONE));
		btnCancel.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent arg0) {
				cancelAction();
			}
		});
		oneself.setDefaultButton(btnSetPassword);
		// Add Listener
		addSelectAllListener(oneself);
		// Set display label of Controls
		setDisplayControlLabel();
	}
	
	/**
	 * Set display language
	 * @param language
	 * @throws IOException
	 */
	private void setDisplayControlLabel() throws IOException {
		if (language.equals(Const.LANGUAGE_EN)) {
			if (this.action == Const.SETUP_PASS || this.action == Const.EDIT_PASS) {
				oneself.setText("Auto Shutdown - Setup password");
				clblSetPassword.setText("New password");
				clblConfirm.setText("Confirm");
			}
			else if (this.action == Const.CHECK_PASS){
				oneself.setText("Auto Shutdown - Check password");
				clblSetPassword.setText("Password");
			}
			if (this.action == Const.SETUP_PASS){
				btnSetPassword.setText("Change");
			}
			else {
				btnSetPassword.setText("Check");
			}
			btnCancel.setText("Cancel");
		}
		else if (language.equals(Const.LANGUAGE_VN)) {
			if (this.action == Const.SETUP_PASS || this.action == Const.EDIT_PASS) {
				oneself.setText("Auto Shutdown - Thiết lập mật khẩu");
				clblSetPassword.setText("Mật khẩu mới");
				clblConfirm.setText("Nhập lại");
			}
			else if (this.action == Const.CHECK_PASS){
				oneself.setText("Auto Shutdown - Kiểm tra mật khẩu");
				clblSetPassword.setText("Mật khẩu");
			}
			if (this.action == Const.SETUP_PASS){
				btnSetPassword.setText("Thiết lập");
			}
			else {
				btnSetPassword.setText("Kiểm tra");
			}
			btnCancel.setText("Quay về");
		}
	}
	
	/**
	 * addSelectAllListener
	 * 
	 * @param ctrl
	 */
	protected void addSelectAllListener(Control ctrl) {
		if (ctrl instanceof Text) {
			ctrl.addFocusListener(new SelectAllFocusAdapter());
		} else if (ctrl instanceof Composite) {
			Composite comp = (Composite) ctrl;
			Control[] children = comp.getChildren();
			if (children != null) {
				for (int i = 0; i < children.length; i++) {
					addSelectAllListener(children[i]);
				}
			}
		}
	}
	
	/**
	 * SelectAllFocusAdapter
	 */
	protected final class SelectAllFocusAdapter extends FocusAdapter {
		/**
		 * SelectAllFocusAdapter
		 */
		public SelectAllFocusAdapter() {
			super();
		}
		/**
		 * focusGained
		 * 
		 * @param e
		 */
		public void focusGained(FocusEvent e) {
			if (e.getSource() instanceof Text) {
				((Text) e.getSource()).selectAll();
			}
		}
	}

	/**
	 * Cancel & close action
	 *
	 */
	private void cancelAction() {
		log.info("Cancel button clicked.");
		this.oneself.dispose();
		this.exitFlag = false;
	}

	/**
	 * set password action
	 *
	 */
	private void setPassAction() {
		if (this.action == Const.SETUP_PASS || this.action == Const.EDIT_PASS){//
			if (Utils.isNullEmpty(txtPassword.getText())){
				if (language.equals(Const.LANGUAGE_EN)) {
					Utils.errorMsgBox("Password must be input.");
				}
				else {
					Utils.errorMsgBox("Mật khẩu phải được nhập.");
				}
				txtPassword.setFocus();
				return;
			}
			if (Utils.isNullEmpty(txtConfirmPass.getText())){
				if (language.equals(Const.LANGUAGE_EN)) {
					Utils.errorMsgBox("Confirm password must be input.");
				}
				else {
					Utils.errorMsgBox("Nhập lại mật khẩu để kiểm tra.");
				}
				txtConfirmPass.setFocus();
				return;
			}
			if (!txtPassword.getText().equals(txtConfirmPass.getText())){
				if (language.equals(Const.LANGUAGE_EN)) {
					Utils.errorMsgBox("Confirm password is different.");
				}
				else {
					Utils.errorMsgBox("Mật khẩu nhập lại không đúng.");
				}
				txtConfirmPass.setFocus();
				return;
			}
			form.setPassword(txtPassword.getText());
		}
		else if (this.action == Const.CHECK_PASS){//check
			if (!form.getPassword().equals(txtPassword.getText())){
				if (language.equals(Const.LANGUAGE_EN)) {
					Utils.errorMsgBox("Incorrect password.");
				}
				else {
					Utils.errorMsgBox("Mật khẩu sai.");
				}
				txtPassword.setFocus();
				return;
			}
			log.info("Input Password OK.");
		}
		//save password
		try {
			if (this.action == Const.SETUP_PASS || this.action == Const.EDIT_PASS){
				ResourceUtil.getInstance().setProperty(Const.KEY_PASSWORD, form.getPassword());
				log.info("Setup password successfully.");
				if (language.equals(Const.LANGUAGE_EN)) {
					Utils.infoMsgBox("Password is changed.");
				}
				else {
					Utils.infoMsgBox("Đã thiết lập mật khẩu mới.");
				}
			}
		} 
		catch (Exception e) {
			log.severe("Exception." + e.getMessage());
		}
		// Close Screen
		this.oneself.dispose();
		this.exitFlag = true;
	}
}
